package cn.itsource.basic.util;


import cn.hutool.extra.spring.SpringUtil;
import cn.itsource.basic.config.exception.BusinessException;
import cn.itsource.org.pojo.loginInfo.LoginInfo;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

/**
 * LoginINfo工具类
 */
public class LoginInfoUtil {

    /**
     * 获取userId
     * @return
     */
    public static Long getUserId(){
        return Optional.ofNullable(getUserInfo().getUserId()).orElseThrow(() -> new BusinessException("用户id获取异常"));
    }

    /**
     * 获取shopId
     * @return
     */
    public static Long getShopId(){
        return Optional.ofNullable(getUserInfo().getShopId()).orElseThrow(() -> new BusinessException("shopId获取异常"));
    }

    /**
     * 获取loginInfo
     * @return
     */
    public static LoginInfo getUserInfo(){
        //1.获取redisService的Spring Bean对象
        RedisService redisService = SpringUtil.getBean(RedisService.class);

        //2.request从哪来 request获取token
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        //2.1获取token
        String token = request.getHeader("token");

        //3.从redis获取loginInfo
        LoginInfo loginInfo = redisService.getKeyObjectValue(token, LoginInfo.class);

        return loginInfo;

    }

}

